package com.simple.study.service.impl;

import com.simple.study.base.dao.MyMapper;
import com.simple.study.base.service.impl.BaseServiceImpl;
import com.simple.study.mapper.PermissionMapper;
import com.simple.study.mapper.RoleMapper;
import com.simple.study.pojo.Permission;
import com.simple.study.pojo.Role;
import com.simple.study.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName RoleServiceImpl
 * @Author SimpleTree
 **/
@Service
public class RoleServiceImpl extends BaseServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public MyMapper getMapper() {
        return roleMapper;
    }

    /**
     * 获取权限列表
     *
     * @return
     */
    @Override
    public List<Role> getRoles() {
        List<Role> roles = roleMapper.selectAll();

        for (Role role : roles) {
            String[] psIds = role.getPsIds().split(",");
            List<Short> idList = new ArrayList<>();
            //将psIds转换为list
            for (String psId : psIds) {
                idList.add(Short.parseShort(psId));
            }

            //获取一级权限
            List<Permission> firstAll = permissionMapper.getPermissionByLevel("0");
            //遍历一级权限,找到二级权限
            for (Permission permission : firstAll) {
                //找到的二级权限
                List<Permission> mid = new ArrayList<>();
                List<Permission> permissionByUnio = permissionMapper.getPermissionByUnio(permission.getId());
                choosePid(permissionByUnio, idList, mid);

                //遍历二级权限
                for (Permission sec : mid) {
                    //找到的二级权限
                    List<Permission> third = new ArrayList<>();
                    List<Permission> thirdList = permissionMapper.getPermissionByUnio(sec.getId());
                    choosePid(thirdList, idList, third);
                    sec.setChildren(third);
                }
                //将二级权限加入到一级权限内
                permission.setChildren(mid);
            }
            List<Permission> list = new ArrayList<>();
            for (int i = 0; i < firstAll.size(); i++) {
                Permission permission = firstAll.get(i);
                if (permission.getChildren() != null && permission.getChildren().size() > 0) {
                    list.add(permission);
                }
            }
            role.setChildren(list);
        }
        return roles;
    }

    public void choosePid(List<Permission> list, List<Short> idList, List<Permission> mid) {
        for (Permission permission : list) {
            if (idList.contains(permission.getId())) {
                mid.add(permission);
            }
        }
    }

}
